package com.jiao.comm.utils;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

/**
 * @Author: vincent.jiao
 * @Date: 2021/6/10
 */
@Component
public class SpringUtils implements ApplicationListener<ContextRefreshedEvent> {
    private static ApplicationContext ctx = null;

    public static ApplicationContext getApplicationContext() {
        return ctx;
    }

    /**
     * 获取指定 bean 名.
     * @param beanName
     * @param <T>
     * @return
     */
    public static <T> T getBean(String beanName) {
        return (T)ctx.getBean(beanName);
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        SpringUtils.ctx = event.getApplicationContext();
    }
}
